<template>
	<view class="withdraw-detail-page">
		<!-- 自定义头部 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-container" @click="closePage()">
					<view class="back-btn">
						<text class="cuIcon-back"></text>
					</view>
					<view class="page-title">
						提现详情
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 主要内容区域 -->
		<view class="content-container">
			<!-- 状态卡片 -->
			<view class="status-card">
				<view class="status-icon" :class="statusIconClassMap[record.status]">
					<text :class="statusIconMap[record.status]"></text>
				</view>
				<view class="status-info">
					<view class="status-text">{{statusTextMap[record.status]}}</view>
					<view class="status-desc">{{statusDescMap[record.status]}}</view>
				</view>
			</view>

			<!-- 金额信息 -->
			<view class="amount-card">
				<view class="amount-header">
					<text class="amount-label">提现金额</text>
				</view>
				<view class="amount-display">
					<text class="currency">￥</text>
					<text class="amount">{{record.amount}}</text>
				</view>
				<view class="amount-breakdown">
					<view class="breakdown-item">
						<text class="item-label">手续费</text>
						<text class="item-value">-￥{{record.fee}}</text>
					</view>
					<view class="breakdown-item">
						<text class="item-label">实际到账</text>
						<text class="item-value actual">￥{{record.actualAmount}}</text>
					</view>
				</view>
			</view>

			<!-- 提现信息 -->
			<view class="info-card">
				<view class="card-header">
					<text class="card-title">提现信息</text>
				</view>
				<view class="info-list">
					<view class="info-item">
						<text class="info-label">提现方式</text>
						<text class="info-value">{{withdrawMethodMap[record.withdrawMethod]}}</text>
					</view>
					<view class="info-item" v-if="record.accountInfo">
						<text class="info-label">收款人</text>
						<text class="info-value">{{record.accountInfo.accountName}}</text>
					</view>
					<view class="info-item" v-if="record.accountInfo">
						<text class="info-label">收款账户</text>
						<text class="info-value">{{maskAccountNumber(record.accountInfo.accountNumber)}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">申请时间</text>
						<text class="info-value">{{formatTime(record.createdAt)}}</text>
					</view>
					<view class="info-item" v-if="record.processInfo && record.processInfo.processTime">
						<text class="info-label">处理时间</text>
						<text class="info-value">{{formatTime(record.processInfo.processTime)}}</text>
					</view>
					<view class="info-item" v-if="record.auditInfo && record.auditInfo.auditRemark">
						<text class="info-label">审核备注</text>
						<text class="info-value">{{record.auditInfo.auditRemark}}</text>
					</view>
					<view class="info-item" v-if="record.processInfo && record.processInfo.processRemark">
						<text class="info-label">处理备注</text>
						<text class="info-value">{{record.processInfo.processRemark}}</text>
					</view>
				</view>
			</view>

			<!-- 微信支付信息（仅微信提现显示） -->
			<view class="wechat-card" v-if="record.withdrawMethod === 'wechat' && record.transferInfo && Object.keys(record.transferInfo).length > 0">
				<view class="card-header">
					<text class="card-title">微信支付信息</text>
				</view>
				<view class="info-list">
					<view class="info-item" v-if="record.transferInfo && record.transferInfo.transferBillNo">
						<text class="info-label">微信转账单号</text>
						<text class="info-value">{{record.transferInfo.transferBillNo}}</text>
					</view>
					<view class="info-item" v-if="record.transferInfo && record.transferInfo.state">
						<text class="info-label">转账状态</text>
						<text class="info-value">{{record.transferInfo.state}}</text>
					</view>
					<view class="info-item" v-if="record.transferInfo && record.transferInfo.createTime">
						<text class="info-label">转账时间</text>
						<text class="info-value">{{formatTime(record.transferInfo.createTime)}}</text>
					</view>
					<view class="info-item" v-if="record.transferInfo && record.transferInfo.mchId">
						<text class="info-label">商户号</text>
						<text class="info-value">{{record.transferInfo.mchId}}</text>
					</view>
					<view class="info-item" v-if="record.processInfo && record.processInfo.processorId">
						<text class="info-label">处理人</text>
						<text class="info-value">{{record.processInfo.processorId.nickname}}</text>
					</view>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons">
				<!-- 失败状态：重新申请 -->
				<button class="retry-btn" v-if="record.status === 'failed'" @click="retryWithdraw" :disabled="loading">
					<text v-if="loading">处理中...</text>
					<text v-else>重新申请</text>
				</button>
				
				<!-- 处理中状态：确认收款 -->
				<button class="confirm-btn" v-if="canShowConfirmButton" @click="confirmReceipt" :disabled="loading">
					<text v-if="loading">处理中...</text>
					<text v-else>确认收款</text>
				</button>
			</view>

			<!-- 联系客服 -->
			<view class="contact-section">
				<button class="contact-btn" open-type="contact">
					<text class="cuIcon-service"></text>
					<text>联系客服</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import headerSlot from '@/components/header-slot.vue';
	import { getWithdrawDetail, retryWithdraw, queryWechatWithdrawStatus, confirmWithdrawReceipt } from '@/api/withdraw.js';
	import Storage from '@/utils/storage.js';
	
	export default {
		components: {
			headerSlot,
		},
		data() {
			return {
				recordId: '',
				record: {
					accountInfo: {},
					processInfo: {},
					auditInfo: {},
					transferInfo: {} // 添加transferInfo初始化
				},
				loading: false,
				statusIconClassMap: {
					pending: 'status-pending',
					processing: 'status-processing',
					success: 'status-success',
					failed: 'status-failed'
				},
				statusIconMap: {
					pending: 'cuIcon-time',
					processing: 'cuIcon-loading',
					success: 'cuIcon-roundcheck',
					failed: 'cuIcon-roundclose'
				},
				statusTextMap: {
					pending: '待审核',
					processing: '处理中',
					success: '提现成功',
					failed: '提现失败'
				},
				statusDescMap: {
					pending: '您的提现申请已提交，等待审核',
					processing: '正在处理您的提现申请，请耐心等待',
					success: '提现已成功到账，请注意查收',
					failed: '提现处理失败，可重新申请'
				},
				withdrawMethodMap: {
					wechat: '微信零钱',
					alipay: '支付宝',
					bank: '银行卡'
				}
			};
		},
		computed: {
			// 检查是否有 packageInfo 字段
			hasPackageInfo() {
				return (
					(this.record.transferInfo && this.record.transferInfo.packageInfo) ||
					(this.record.processInfo && this.record.processInfo.packageInfo) ||
					(this.record.processInfo && this.record.processInfo.package_info)
				);
			},
			// 检查是否可以显示确认收款按钮
			canShowConfirmButton() {
				return this.record.status === 'processing' && 
					   this.record.withdrawMethod === 'wechat' && 
					   this.record.processInfo && 
					   this.record.processInfo.transactionId;
			}
		},
		onLoad(options) {
			this.recordId = options.id
			this.loadDetail()
		},
		methods: {
			closePage() {
				uni.navigateBack()
			},
			
			// 加载详情
			async loadDetail() {
				if (!this.recordId) return
				
				try {
					this.loading = true
					uni.showLoading({
						title: '加载中...'
					})
					
					const response = await getWithdrawDetail(this.recordId)
					
					
					if (response.statusCode && response.data.data) {
						this.record = response.data.data
						
						
						// 详细检查数据结构
						
						
						// 检查是否有其他可能的字段名
						
						
						// 检查 processInfo 中的字段
						if (this.record.processInfo) {
							
						}
						
						// 如果是微信提现且状态为处理中，查询微信状态
						if (this.record.withdrawMethod === 'wechat' && this.record.status === 'processing' && !this.record.processInfo) {
							await this.queryWechatStatus()
						}
					} else {
	
						uni.showToast({
							title: '获取详情失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('获取详情失败:', error)
					uni.showToast({
						title: '获取详情失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					uni.hideLoading()
				}
			},
			
			// 查询微信状态
			async queryWechatStatus() {
				try {
					const response = await queryWechatWithdrawStatus(this.recordId)
					if (response.success && response.data) {
						// 更新处理信息
						this.record.processInfo = response.data.processInfo
		
					}
				} catch (error) {
					console.error('查询微信状态失败:', error)
				}
			},
			
			// 重新申请提现
			async retryWithdraw() {
				try {
					uni.showModal({
						title: '重新申请',
						content: '确定要重新申请这笔提现吗？',
						success: async (res) => {
							if (res.confirm) {
								this.loading = true
								uni.showLoading({
									title: '处理中...'
								})
								
								const response = await retryWithdraw(this.recordId)
								
								uni.hideLoading()
								
								if (response.success) {
									uni.showToast({
										title: '重新申请成功',
										icon: 'success'
									})
									// 刷新详情
									setTimeout(() => {
										this.loadDetail()
									}, 1000)
								} else {
									uni.showToast({
										title: response.message || '重新申请失败',
										icon: 'none'
									})
								}
							}
						}
					})
				} catch (error) {
					console.error('重新申请失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '重新申请失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},
			
			// 确认收款
			// 由于后端没有提供 packageInfo 字段，暂时使用传统确认方式
			// 参考文档：https://pay.weixin.qq.com/doc/v3/merchant/4012716430
			// 
			// TODO: 后端需要修复的问题
			// 1. 在微信转账时生成并返回 packageInfo 字段
			// 2. 在 processInfo 中添加 mchId 字段
			// 3. 确保 transferInfo 字段正确返回
			// 
			// 当前后端返回的数据结构：
			// processInfo: {
			//   processRemark: "微信转账已发起，等待用户确认",
			//   processTime: "2025-08-04T05:08:20.768Z",
			//   processorId: {...},
			//   transactionId: "TB1754284099756667"
			//   // 缺少: packageInfo, mchId
			// }
			async confirmReceipt() {

				
				// 检查是否有 packageInfo 字段（用于微信官方确认）
				let packageInfo = (this.record.transferInfo && this.record.transferInfo.packageInfo) ||
								 (this.record.processInfo && this.record.processInfo.packageInfo) ||
								 (this.record.processInfo && this.record.processInfo.package_info);
				

				
				if (packageInfo) {

					let mchId = (this.record.transferInfo && this.record.transferInfo.mchId) ||
							   (this.record.processInfo && this.record.processInfo.mchId) ||
							   '1230000000';
					this.requestWechatConfirm(packageInfo, mchId);
				} else {

					// 直接更新收款状态
					await this.updateReceiptStatus();
				}
			},

			// 唤起微信官方确认收款
			requestWechatConfirm(packageInfo, mchId) {

				
				// #ifdef MP-WEIXIN
				const canUseAPI = wx.canIUse('requestMerchantTransfer');
				const accountInfo = wx.getAccountInfoSync();
				const miniProgramAppId = (accountInfo && accountInfo.miniProgram && accountInfo.miniProgram.appId);
				

				
				if (canUseAPI) {
					const finalMchId = mchId || 
									  (this.record.transferInfo && this.record.transferInfo.mchId) || 
									  (this.record.processInfo && this.record.processInfo.mchId) || 
									  '1230000000';

					
					// 参数验证
					if (!packageInfo || !finalMchId || !miniProgramAppId) {
						
						return;
					}
					

					
					wx.requestMerchantTransfer({
						mchId: finalMchId,
						appId: miniProgramAppId,
						package: packageInfo,
						success: (res) => {
							
							
							// res.err_msg将在页面展示成功后返回应用时返回ok，并不代表付款成功
							if (res.err_msg === 'requestMerchantTransfer:ok') {
	
								// 用户确认后，调用后端接口更新状态
								this.updateReceiptStatus();
							} else if (res.err_msg === 'requestMerchantTransfer:cancel') {

							} else {

								// 如果唤起失败，回退到传统确认方式
							}
						},
						fail: (res) => {
							
							// 如果唤起失败，回退到传统确认方式
						}
					});
				} else {

					uni.showModal({
						title: '提示',
						content: '你的微信版本过低，请更新至最新版本。',
						showCancel: false,
						success: () => {
							// 直接更新收款状态
							this.updateReceiptStatus();
						}
					});
				}
				// #endif
				
				// #ifndef MP-WEIXIN

				// 非微信小程序环境，直接更新收款状态
				this.updateReceiptStatus();
				// #endif
			},



			// 更新收款状态
			async updateReceiptStatus() {
				this.loading = true;
				uni.showLoading({
					title: '处理中...'
				});
				
				try {
					const response = await confirmWithdrawReceipt(this.recordId);
					
					uni.hideLoading();
					
					if (response.success) {
						uni.showToast({
							title: '确认收款成功',
							icon: 'success'
						});
						// 刷新详情
						setTimeout(() => {
							this.loadDetail();
						}, 1000);
					} else {
						uni.showToast({
							title: response.message || '确认收款失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('确认收款失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '确认收款失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 掩码账户号码
			maskAccountNumber(accountNumber) {
				if (!accountNumber || typeof accountNumber !== 'string') return ''
				if (accountNumber.length <= 8) return accountNumber
				return accountNumber.substring(0, 4) + '****' + accountNumber.substring(accountNumber.length - 4)
			},

			// 格式化时间
			formatTime(timeString) {
				if (!timeString) return ''
				const date = new Date(timeString)
				return date.toLocaleString('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit'
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.withdraw-detail-page {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.header-container {
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		width: 100%;
		height: 88rpx;
		
		.back-btn {
			margin-right: 20rpx;
			padding: 8rpx;
			
			.cuIcon-back {
				font-size: 36rpx;
				color: #2C2622;
			}
		}
		
		.page-title {
			font-weight: 600;
			font-size: 36rpx;
			color: #2C2622;
		}
	}

	.content-container {
		padding: 32rpx;
	}

	.status-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 48rpx 32rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		display: flex;
		align-items: center;
		
		.status-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 32rpx;
			
			&.status-pending {
				background: #fff7e6;
				color: #fa8c16;
			}
			
			&.status-processing {
				background: #e6f7ff;
				color: #1890ff;
			}
			
			&.status-success {
				background: #f6ffed;
				color: #52c41a;
			}
			
			&.status-failed {
				background: #fff2f0;
				color: #ff4d4f;
			}
			
			text {
				font-size: 40rpx;
			}
		}
		
		.status-info {
			flex: 1;
			
			.status-text {
				font-size: 36rpx;
				color: #2C2622;
				font-weight: 600;
				margin-bottom: 8rpx;
			}
			
			.status-desc {
				font-size: 28rpx;
				color: #909399;
			}
		}
	}

	.amount-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		
		.amount-header {
			margin-bottom: 24rpx;
			
			.amount-label {
				font-size: 28rpx;
				color: #909399;
			}
		}
		
		.amount-display {
			display: flex;
			align-items: baseline;
			margin-bottom: 32rpx;
			
			.currency {
				font-size: 48rpx;
				color: #2C2622;
				font-weight: 600;
			}
			
			.amount {
				font-size: 72rpx;
				color: #2C2622;
				font-weight: 700;
			}
		}
		
		.amount-breakdown {
			border-top: 1rpx solid #f0f0f0;
			padding-top: 24rpx;
			
			.breakdown-item {
				display: flex;
				justify-content: space-between;
				margin-bottom: 16rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.item-label {
					font-size: 28rpx;
					color: #606266;
				}
				
				.item-value {
					font-size: 28rpx;
					color: #2C2622;
					font-weight: 600;
					
					&.actual {
						color: #FE6100;
						font-size: 32rpx;
					}
				}
			}
		}
	}

	.info-card, .wechat-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
		
		.card-header {
			margin-bottom: 24rpx;
			
			.card-title {
				font-size: 32rpx;
				color: #2C2622;
				font-weight: 600;
			}
		}
		
		.info-list {
			.info-item {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.info-label {
					font-size: 28rpx;
					color: #909399;
				}
				
				.info-value {
					font-size: 28rpx;
					color: #2C2622;
					max-width: 60%;
					text-align: right;
					word-break: break-all;
				}
			}
		}
	}

	.action-buttons {
		margin-bottom: 32rpx;
		
		.retry-btn, .confirm-btn {
			width: 100%;
			height: 88rpx;
			border-radius: 16rpx;
			font-size: 32rpx;
			font-weight: 600;
			display: flex;
			align-items: center;
			justify-content: center;
			
			&:active {
				transform: scale(0.98);
			}
			
			&:disabled {
				opacity: 0.6;
			}
		}
		
		.retry-btn {
			background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
			color: #FFFFFF;
		}
		
		.confirm-btn {
			background: linear-gradient(135deg, #07C160 0%, #10AD6A 100%);
			color: #FFFFFF;
		}
	}

	.contact-section {
		.contact-btn {
			width: 100%;
			height: 88rpx;
			background: #f8f9fa;
			color: #606266;
			border: 2rpx solid #e9ecef;
			border-radius: 16rpx;
			font-size: 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.cuIcon-service {
				margin-right: 12rpx;
				font-size: 36rpx;
			}
			
			&:active {
				background: #e9ecef;
			}
		}
	}
</style> 